package com.fudan.adse.controller;


import cn.hutool.core.collection.CollUtil;
import com.fudan.adse.api.CommonResult;
import com.fudan.adse.domain.bo.OAuthTokenBO;
import com.fudan.adse.domain.dto.UserLoginParam;
import com.fudan.adse.domain.dto.UserParam;
import com.fudan.adse.domain.po.Role;
import com.fudan.adse.domain.po.User;
import com.fudan.adse.domain.vo.UserVO;
import com.fudan.adse.service.RoleService;
import com.fudan.adse.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author Jerry Zhang <zhangjian16@fudan.edu.cn>
 * @desc 用户模块控制器，控制用户登录、登出，获取用户信息，更新用户信息等
 * @date 2022-09-14 11:56
 */
@RestController
@RequestMapping("/api/v1/ums")
public class UmsController {
    private UserService userService;
    private RoleService roleService;


    /**
     * 登录以后返回token
     *
     * @param loginParam
     * @return
     */
    @PostMapping(value = "/login")
    public CommonResult login(@Validated @RequestBody UserLoginParam loginParam) {
        return userService.login(loginParam.getUsername(), loginParam.getPassword());
    }

    /**
     * 在Request Body中以json格式发送用户的具体信息，以向系统中添加用户
     *
     * @param param 用户信息
     * @return
     */
    @PostMapping(value = "/register")
    public CommonResult<String> addUser(@Validated @RequestBody UserParam param) {
        return CommonResult.success(userService.addUser(param));
    }

    @GetMapping(value = "/user")
    public CommonResult<UserVO> getUserInfo(@NotBlank @RequestParam("username") String username) {
        UserVO userVO = userService.getUserByUsername(username);
        userVO.setMenus(roleService.getMenuList(userVO.getId()));
        List<Role> roles = userService.getRoleList(userVO.getId());
        if (CollUtil.isNotEmpty(roles)) {
            userVO.setRoles(roles.stream().map(Role::getRoleName).collect(Collectors.toList()));
        }
        return CommonResult.success(userVO);
    }

    @GetMapping(value = "/user/all")
    public CommonResult<List<UserVO>> getAllUser() {
        return CommonResult.success(userService.getAllUsers());
    }

    @PutMapping(value = "/user")
    public CommonResult<Object> updateUserDetail(@Validated @RequestBody User user) {
        userService.updateUser(user);
        return CommonResult.success(null);
    }


    @DeleteMapping(value = "/user")
    public CommonResult<Object> deleteUser(@NotBlank @RequestParam("username") String username) {
        userService.deleteUser(username);
        return CommonResult.success(null);
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
}
